package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.auth.constants.JwtConstants.COOKIE_NAME;
import static com.leyou.auth.constants.JwtConstants.KEY_PREFIX;

/**
 * @author YYP
 * @date 2021/1/11
 */
@Service
@Slf4j
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            //取不到token,说明token已经失效了
            String token = CookieUtils.getCookieValue(request, COOKIE_NAME);

            Payload payload = jwtUtils.parseJwt(token);

            String key = KEY_PREFIX + payload.getUserDetail().getId();

            this.redisTemplate.delete(key);

            log.info("用户退出服务端成功,redis信息删除");
        } catch (Exception e) {
        }

        //重新生成cookie


        Cookie cookie = new Cookie(COOKIE_NAME, "");
        cookie.setDomain(JwtConstants.DOMAIN);
        //cookie的生效路径,/代表一切路径
        cookie.setPath("/");
        //拒绝脚本访问
        cookie.setHttpOnly(true);
        // cookie有效期，-1就是跟随当前会话，浏览器关闭就消失;0立即失效删除
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    @Override
    public void userLogin(String username, String password, HttpServletResponse response) {

        // 1.授权中心携带用户名密码，到用户中心查询用户
        UserDTO userDTO = null;

        try {
            userDTO = userClient.queryUser(username, password);
        } catch (FeignException e) {
           throw new LyException(e.status(),e.getMessage());
        }
        // 2.校验查询结果
        if (userDTO == null) {
            throw new LyException(400,"用户名名或者密码错误");
        }

        // 3.如果正确，生成JWT凭证，查询错误则返回400
        // 3.1.准备用户信息
        UserDetail userDetail = new UserDetail();
        userDetail.setId(userDTO.getId());
        userDetail.setUsername(userDTO.getUsername());
        //3.2生成jwt(token)
        String token = jwtUtils.createJwt(userDetail);
        //4.把token写入cookie中
        writeCookie(response,token);

    }

    public void writeCookie(HttpServletResponse response,String token) {
        Cookie cookie = new Cookie(COOKIE_NAME, token);
        //cookie适配的域名，子域名也有效，item.leyou.com
        cookie.setDomain(JwtConstants.DOMAIN);
        //cookie的生效路径,/代表一切路径
        cookie.setPath("/");
        //拒绝脚本访问
        cookie.setHttpOnly(true);
        // cookie有效期，-1就是跟随当前会话，浏览器关闭就消失
//        cookie.setMaxAge(-1);

        response.addCookie(cookie);
    }
}
